package com.example.projectmanagement.service.study;

import com.example.projectmanagement.model.study.UserCourseEnrollment;
import com.example.projectmanagement.model.study.Course;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.repository.study.UserCourseEnrollmentRepository;
import com.example.projectmanagement.repository.study.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class EnrollmentService {

    @Autowired
private UserCourseEnrollmentRepository enrollmentRepository;
    
    @Autowired
    private CourseRepository courseRepository;

    /**
     * 用户报名课程
     */
    @Transactional
    public UserCourseEnrollment enrollUserToCourse(User user, Long courseId) {
        // 检查课程是否存在
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found with id: " + courseId));
        
        // 检查用户是否已经报名该课程
        Optional<UserCourseEnrollment> existingEnrollment = enrollmentRepository.findByUserAndCourse(user, course);
        if (existingEnrollment.isPresent()) {
            throw new RuntimeException("User is already enrolled in this course");
        }
        
        // 创建新的报名记录
        UserCourseEnrollment enrollment = new UserCourseEnrollment();
        enrollment.setUser(user);
        enrollment.setCourse(course);
        enrollment.setEnrollmentStatus("ENROLLED"); // 已报名
        enrollment.setEnrollmentDate(LocalDateTime.now());
        
        // 获取课程总课时数
        // 这里需要调用ContentService来获取总课时数，暂时设置为0
        enrollment.setTotalLessons(0);
        
        return enrollmentRepository.save(enrollment);
    }

    /**
     * 获取用户的课程报名列表
     */
    public Page<UserCourseEnrollment> getUserEnrollments(User user, Pageable pageable) {
        return enrollmentRepository.findByUser(user, pageable);
    }

    /**
     * 获取用户的所有课程报名（不分页）
     */
    public List<UserCourseEnrollment> getUserEnrollments(User user) {
        return enrollmentRepository.findByUser(user);
    }

    /**
     * 获取课程的所有报名用户
     */
    public Page<UserCourseEnrollment> getCourseEnrollments(Long courseId, Pageable pageable) {
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found with id: " + courseId));
        return enrollmentRepository.findByCourse(course, pageable);
    }

    /**
     * 根据用户和课程获取报名记录
     */
    public Optional<UserCourseEnrollment> getEnrollmentByUserAndCourse(User user, Long courseId) {
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found with id: " + courseId));
        return enrollmentRepository.findByUserAndCourse(user, course);
    }

    /**
     * 更新报名状态
     */
    @Transactional
    public UserCourseEnrollment updateEnrollmentStatus(User user, Long courseId, String status) {
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found with id: " + courseId));
        
        UserCourseEnrollment enrollment = enrollmentRepository.findByUserAndCourse(user, course)
                .orElseThrow(() -> new RuntimeException("Enrollment not found for user and course"));
        
        enrollment.setEnrollmentStatus(status);
        
        if ("COMPLETED".equals(status) && enrollment.getCompletionDate() == null) {
            enrollment.setCompletionDate(LocalDateTime.now());
        }
        
        return enrollmentRepository.save(enrollment);
    }

    /**
     * 更新学习进度
     */
    @Transactional
    public UserCourseEnrollment updateProgress(User user, Long courseId, Integer progressPercentage, 
                                              Integer completedLessons, Integer totalLessons) {
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found with id: " + courseId));
        
        UserCourseEnrollment enrollment = enrollmentRepository.findByUserAndCourse(user, course)
                .orElseThrow(() -> new RuntimeException("Enrollment not found for user and course"));
        
        enrollment.setProgressPercentage(progressPercentage);
        enrollment.setCompletedLessons(completedLessons);
        enrollment.setTotalLessons(totalLessons);
        
        // 如果进度达到100%，自动更新状态为已完成
        if (progressPercentage != null && progressPercentage >= 100) {
            enrollment.setEnrollmentStatus("COMPLETED");
            if (enrollment.getCompletionDate() == null) {
                enrollment.setCompletionDate(LocalDateTime.now());
            }
        } else if (enrollment.getEnrollmentStatus().equals("COMPLETED")) {
            // 如果进度未达到100%但状态是已完成，则更新状态为学习中
            enrollment.setEnrollmentStatus("IN_PROGRESS");
            enrollment.setCompletionDate(null);
        }
        
        return enrollmentRepository.save(enrollment);
    }

    /**
     * 取消课程报名
     */
    @Transactional
    public void cancelEnrollment(User user, Long courseId) {
        Course course = courseRepository.findById(courseId)
                .orElseThrow(() -> new RuntimeException("Course not found with id: " + courseId));
        
        UserCourseEnrollment enrollment = enrollmentRepository.findByUserAndCourse(user, course)
                .orElseThrow(() -> new RuntimeException("Enrollment not found for user and course"));
        
        enrollmentRepository.delete(enrollment);
    }

    /**
     * 获取用户已完成的课程数量
     */
    public Integer getCompletedCoursesCount(Long userId) {
        return enrollmentRepository.countCompletedCoursesByUserId(userId);
    }

    /**
     * 获取课程已完成的报名数量
     */
    public Integer getCompletedEnrollmentsCount(Long courseId) {
        return enrollmentRepository.countCompletedEnrollmentsByCourseId(courseId);
    }
}